use std::{collections::HashMap, fmt::format};

use crate::*;
use common::SubFutureInfo;
use leptos::leptos_dom::ev::SubmitEvent;
use leptos::logging;
use leptos::*;
use serde::{Deserialize, Serialize};
use serde_json::*;
use tracing::{debug, error, info};
use wasm_bindgen::prelude::*;
// use markdown::*;
use comrak::{markdown_to_html, Options};

/**
 * pulldown-cmark 简单而快速。 
 * comrak 复杂而强大。
 * 从生态上看，pulldown-cmark 融入 cargo doc / mdbook 工具。
 * comrak 不仅是一个 parser 还是一个 formatter，或许更适合转成复杂（功能更多）的 html
 
 https://github.com/kivikakk/comrak#related-projects
 https://docs.rs/comrak/latest/comrak/struct.ExtensionOptions.html

Comrak additionally supports its own extensions:
 Superscript
 Header IDs
 Footnotes
 Description lists
 Front matter
 Multi-line blockquotes
 Math
 Emoji shortcodes
 Wikilinks
 Underline
 Table
 ... ...
By default none are enabled(默认都是不支持的！！！， 需要如下设置：);

```rust
let mut options = Options::default();
options.extension.table = true;
let html_src = markdown_to_html(&src, &options);
```
*/
#[component]
pub fn MarkdownPage() -> impl IntoView {

  fn alert(msg: impl AsRef<str>) {
    // let _ = window().alert_with_message(msg.as_ref());
    let _= window().confirm_with_message(msg.as_ref());    
  }

  let table_src = r#"
# Table

| Name | Age |
| ---- | --- |
| Bob  | 27  |
| Alice | 23 |

# Maths

$`1 + 2`$

x^2

$1 + 2$ and $$x = y$$

$$ \int_a^b f(x) \, dx $$
"#;

  let (content, set_content) = create_signal(table_src.to_string());
  
  let src = r###"Hello, World!
This is a **Markdown** example.

- Item 1
- Item 2
- Item 3
  "###;

  let maths_src = r#"      
      Inline 行内的公式 $E=mc^2$ 行内的公式，行内的$E=mc^2$公式。<BR>

      $$c = \pm\sqrt{a^2 + b^2}$$ <BR>

      $$(\sqrt{3x-1}+(1+x)^2)$$ <BR>

      $$x_{1,2}=\frac{-b\pm\sqrt{\color{Red}b^2-4ac}}{2a}$$ <BR>
      
      $${\color{Blue}x^2}+{\color{YellowOrange}2x}-{\color{OliveGreen}1}$$      
      "#;
  // let html_src =  markdown::to_html(src);
  
  let mut options = Options::default();
  options.extension.strikethrough = true;
  let html_src = markdown_to_html(&src, &options);

  let content_src = move || content.get();
    view! {         
      <div id="markdown-input" class="chat-line">
      </div>
      <div id="markdown-id" class="chat-line">
      </div>
      <div align="center">
      <button on:click=move |_| {
        alert("hello,alert!");
      }>alert
      </button>
    
      <button on:click=move |_| {
        // let doc = window().document().unwrap();
        let doc = document();
        let div = doc.get_element_by_id("markdown-id").unwrap();
        div.set_inner_html(&html_src);
        //let _= doc.set_text_content(Some(&html_src));    
        let div = doc.get_element_by_id("div-math").unwrap();
        div.set_inner_html(&maths_src);
      }> markdown example
      </button>

      <button on:click=move |_| {
        let src = content.get();        
        let mut options = Options::default();
        options.extension.table = true;
        options.extension.math_dollars = true;
        options.extension.math_code = true;

        let html_src = markdown_to_html(&src, &options);
        // let html_src =  markdown::to_html(content.get().as_str());
        logging::log!("markdown to html: {:?}", html_src);
        let doc = document(); // window().document().unwrap();
        let div = doc.get_element_by_id("markdown-input").unwrap();
        div.set_inner_html(&html_src);
        //let _= doc.set_text_content(Some(&html_src));      
      }> markdown input
      </button>
      </div>
      <div id="div-math">
      </div>    
      <div align="center"><textarea cols=120 rows=12 on:input=move |ev| {
        let val = event_target_value(&ev);
        logging::log!("{:?}", val);
        set_content.set(val);        
      }
      >
      {content_src()}
      </textarea>
      </div>     
      <div align="center">
      <p> Math: <a href="https://developer.mozilla.org/en-US/docs/Web/MathML"  target="_blank"> MathML </a>      </p>
      <math display="block">
        <mfrac>
          <mrow>
            <mi>a</mi>
            <mo>+</mo>
            <mn>2</mn>
          </mrow>
          <mrow>
            <mn>3</mn>
            <mo>-</mo>
            <mi>b</mi>
          </mrow>
        </mfrac>
      </math>
      </div>   
    }
}
